﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

/*
    使用方法:
 
        1. 添加MultiDownloder Prefab
        2. 连接MultiDownloder
  
    代码例子:
 
        multiDownloader.Download("http://192.168.1.128:9888/images/zipInfo.json");
        multiDownloader.EventMultiDownloadSuccess += OnMultiDownloadSuccess;
        multiDownloader.EventMultiDownloadFail += OnMultiDownloadFail;

        private void OnMultiDownloadSuccess()
        {
            Debug.Log("---- OnMultiDownloadSuccess");
        }

        private void OnMultiDownloadFail(int error)
        {
            Debug.Log("---- OnMultiDownloadFail");
        }      
    
    备注:
        1. 下载的是json文件
        2. 文件格式
 *  [
        { "path" : "ios__v21_1__to__v21_19.zip", "md5" : "c4b9d82fb0448bf2ba5b27184235ffac"},
        { "path" : "ios__v21_13__to__v21_19.zip", "md5" : "f16889410621df8bc92265ae5d4e5fa6"}
    ]
 *.
 
    todo : 1. md5 检测
           2. 临时文件名称（方便统一删除）.
 *         3. json 文件正确性检测
 *         4. ios 真机测试
 *         
*/

public class MultiDownloder : MonoBehaviour
{
    public  int                             maxRetryCount = 3;
    private Dictionary<string, string>      hash;
    public Downloader                       downloader;
    private int                             retryCount;
   
    #region Public Interface

    public void DownloadJson(string url)
    {
        retryCount = maxRetryCount;
        Debug.Log("[MultiDownloder] downloadJson");
        downloader.EventDownloadSuccess += OnDownloadSuccess;
        downloader.EventDownloadFail += OnDownloadFail;
        downloader.EventDownloadProgress += OnDownloadProgress;
        downloader.Download(url);
    }

    #endregion // #region Public Interface

    #region Private Methods

    private void OnDownloadProgress(float value)
    {
        Debug.Log("-- OnDownloadProgress : " + value);
    }

    private void OnDownloadSuccess(string url)
    {
        retryCount = maxRetryCount;
        Debug.Log("-- OnDownloadSucess ");

        // ui show uncompress
        Debug.Log("--- decode json");
        if (url.Contains(".json") || url.Contains(".JSON"))
        {
            string path = Downloader.Url2FileName(url);
            string content = File.ReadAllText(path);
            string hostName = GetHostName(url);
            JSONObject json = new JSONObject(content);
            hash = Json2Dictionary(json, hostName);
        }

        if (hash.ContainsKey(url))
        {
            hash.Remove(url);
        }
        Debug.Log("[MultiDownloder] finish download " + url);
            
        if (hash.Keys.Count == 0)
        {
            Debug.Log("[MultiDownloder] download success!");
            if (EventMultiDownloadSuccess != null)
            {
                EventMultiDownloadSuccess();
            }
        }
        else
        {
            string key = GetNextUrl(hash);
            downloader.Download(key);
        }
    }

    private void OnDownloadFail(string url)
    {
        Debug.Log("-- OnDownloadFail ");
        if (retryCount <= 0)
        {
            if (EventMultiDownloadFail != null)
            {
                EventMultiDownloadFail();
            }
        }
        else
        {
            downloader.Download(url);
            retryCount--;
        }
    }

    private string GetNextUrl(Dictionary<string, string> dictionay)
    {
        Dictionary<string, string>.KeyCollection names = hash.Keys;

        foreach (string name in names)
        {
            return name;
        }
        return "";
    }

    /**
        * "http://www.baidu.com/1.txt" => "http://www.baidu.com/"
        */

    private string GetHostName(string url)
    {
        string filename = Path.GetFileName(url);
        return url.Substring(0, url.Length - filename.Length);
    }

    private Dictionary<string,string> Json2Dictionary(JSONObject json, string hostname)
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        for (int i = 0; i < json.Count; i++)
        {
            JSONObject obj = json[i];
            Debug.Log("path : " + obj["path"].str + " md5: " + obj["md5"].str);
            string path = obj["path"].str;
            string md5 = obj["md5"].str;
            if (!path.Contains("http://"))
            {
                path = hostname + path;
            }
            Debug.Log("[after ]path  : " + path + " md5: " + md5);                    
            dictionary.Add(path, md5);
        }

        return dictionary;
    }

    #endregion // #region Private Methods

    #region Outlet Methods

    public delegate void OnMultiDownloadSucces();
    public delegate void OnMultiDownloadFail();

    public event OnMultiDownloadSucces EventMultiDownloadSuccess;
    public event OnMultiDownloadFail EventMultiDownloadFail;

    #endregion
}

